import os
import os.path
import logging

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.2')
from django.utils import simplejson as json

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

class IndexPage(webapp.RequestHandler):
    def get(self):
        dirs = os.listdir("./json")
        pages = []
        for dir in dirs:
            if not dir.startswith("."):
                page = {}
                page["name"] = dir
                page["link"] = "/play?g=%s" % dir
                pages.append(page)
        
        self.response.headers['Content-Type'] = 'text/html'
        self.response.out.write(template.render("list.html", {"pages": pages}))

        
class PlayPage(webapp.RequestHandler):

    def detectLang(self):
        
        lang = self.request.get("hl", default_value='en')
        #if self.request.headers.has_key(accept_lang):
        #    str = self.request.headers[accept_lang]
        #    logging.info("accept lang: %s\n" % str)
        #else:
        #    logging.info("no Accept-Language header \n")
        return lang

    def get(self):
        game = self.request.get("g", default_value='test')
        
        lang = self.detectLang();
        template_values = {}
        
        # add site info
        site_json = json.loads(file("./lang.json").read())
        for key in site_json.keys():
            template_values[key] = site_json[key][lang];
        
        # add game info
        game_dir = os.path.join("swf", game)
        template_values["game_swf"] = "./swf/%s/%s.swf" %(game, game)
        game_json = json.loads(file("./json/%s/lang.json" % game).read())
        for key in game_json.keys():
            template_values[key] = game_json[key][lang];
        
        self.response.headers['Content-Type'] = 'text/html'
        self.response.out.write(template.render("play.html", template_values))
        
application = webapp.WSGIApplication(
                                     [('/', IndexPage),
                                      ('/play', PlayPage),],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()